﻿namespace HuwmanCode

open System

[<RequireQualifiedAccess>]
module Array =
    /// Computes the nth element in the array
    let nth index (source:'t array) =
        source.[index]

    /// Computes the nth element in the array
    let nthOrDefault index (source:'t array) =
        if index < source.Length then source.[index]
        else Unchecked.defaultof<'t>

    /// Computes the nth element in the array
    let nthOrNone index (source:'t array) =
        if index < source.Length then Some source.[index]
        else None

    /// Computes the nth element from the end of the array
    let nthFromEnd index (source:'t array) =
        let lastIndex = source.Length - 1
        source.[lastIndex - index]

    /// Computes the nth element from the end of the array
    let nthFromEndOrDefault index (source:'t array) =
        let lastIndex = source.Length - 1
        if lastIndex >= 0 && index <= lastIndex then source.[lastIndex - index]
        else Unchecked.defaultof<'t>

    /// Computes the nth element from the end of the array
    let nthFromEndOrNone index (source:'t array) =
        let lastIndex = source.Length - 1
        if lastIndex >= 0 && index <= lastIndex then Some source.[lastIndex - index]
        else None
    